//
//  ViewController.m
//  JavaScriptCore_demo
//
//  Created by shaoting on 16/3/5.
//  Copyright © 2016年 9elephas. All rights reserved.
//

#import "ViewController.h"
#import "WXApi.h"
#import "HTTPSecssionManger.h"
#import "WXUtil.h"
#import <WebKit/WebKit.h>

#define WeiXinKey @""

@interface ViewController ()<UIWebViewDelegate,WKNavigationDelegate,WKUIDelegate>
{
    NSString * path;
    
    NSString *Test;
    
    NSInteger number;
    
}
@property(nonatomic,strong)NSMutableArray *data;
@property(nonatomic,strong)NSMutableDictionary *dict;
@property(nonatomic,strong)NSMutableArray *dict1;


@end

@implementation ViewController

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(recive:) name:@"valueChange" object:nil];

}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    [self initWed];
    
}

-(void)recive:(NSNotification*)nofi
{
    NSLog(@"%@",nofi);
    
}
-(void)initWed
{
    path = [[NSBundle mainBundle] pathForResource:@"Test.html" ofType:nil];
    NSURL * url = [[NSURL alloc]initFileURLWithPath:path];
    
    UIWebView * webView = [[UIWebView alloc]init];
    webView.frame = CGRectMake(0, 22, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height);
//    webView.UIDelegate = self;
//    webView.navigationDelegate = self;
    webView.delegate = self;
    
    NSURLRequest *requet1 = [NSURLRequest requestWithURL:url];
    
    [webView loadRequest:requet1];
    
    [self.view addSubview:webView];

}
#pragma UIWebViewDelegate方法
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    NSLog(@"开始响应请求时触发");
    return YES;
}
- (void)webViewDidStartLoad:(UIWebView *)webView{
    NSLog(@"开始加载网页");
}
- (void)webViewDidFinishLoad:(UIWebView *)webView{
    NSLog(@"网页加载完毕");
    //获取js的运行环境
    _context=[webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    
    _context[@"test3"] = ^(){
        //   NSArray * args = [JSContext currentArguments];//传过来的参数
        
        NSLog(@"test3");
    };
    
    
    _context[@"test4"] = ^(){
        //   NSArray * args = [JSContext currentArguments];//传过来的参数
        
        NSLog(@"test4");
    };
    
    
    _context[@"test2"] = ^(){
     //   NSArray * args = [JSContext currentArguments];//传过来的参数
    
        if (![WXApi isWXAppInstalled]) {
            NSLog(@"没有安装微信");
            return;
        }else if (![WXApi isWXAppSupportApi]){
            NSLog(@"不支持微信支付");
            return;
        }
        
        
        [[HTTPSecssionManger sharedManager]POST: @"http://h5.aglhz.com/gc_community/member/pay/createTestPayJSON.do" params:nil result:^(id responseObj, NSError *error) {
            
            if(error){
                //        NSLog(@"错误----%@",error);
                return;
            }
            
            NSDictionary *dict1 = [NSJSONSerialization JSONObjectWithData:responseObj options:NSJSONReadingMutableContainers error:nil];
            
            NSLog(@"%@",dict1[@"data"][@"sign"]);
            
            NSString *stamp1 =dict1[@"data"][@"timeStamp"];
            NSLog(@"%d",stamp1.intValue);

            PayReq* req             = [[PayReq alloc] init];
                time_t now;
                time(&now);
                NSString * timeStamp =[NSString stringWithFormat:@"%ld",now];

                req.openID              = @"wxe5dbac804d7bb267";
                req.partnerId           = dict1[@"data"][@"partnerid"];
                req.prepayId            = dict1[@"data"][@"prepayid"];
                req.nonceStr            = dict1[@"data"][@"noncestr"];
                req.timeStamp           = [timeStamp intValue];
                req.package             = @"Sign=WXPay";
                req.sign                = dict1[@"data"][@"sign"];
            
                NSLog(@"appid=%@\npartid=%@\nprepayid=%@\nnoncestr=%@\ntimestamp=%ld\npackage=%@\nsign=%@",[dict1 objectForKey:@"appid"],req.partnerId,req.prepayId,req.nonceStr,(long)req.timeStamp,req.package,req.sign );

            
            // 构造参数列表
            NSMutableDictionary *params = [NSMutableDictionary dictionary];
            [params setObject:@"wxe5dbac804d7bb267" forKey:@"appid"];
            [params setObject:req.partnerId forKey:@"partnerid"];
            [params setObject:req.prepayId forKey:@"prepayid"];
            [params setObject:req.package forKey:@"package"];
            [params setObject:req.nonceStr forKey:@"noncestr"];
            [params setObject:timeStamp forKey:@"timestamp"];
            req.sign = [self genSign:params];
            BOOL bs = [WXApi isWXAppSupportApi];
            if (bs) {
                BOOL isok = [WXApi sendReq:req];
                if (isok) {
                    
                }else{
//                    [self PushFailAlertView:@"微信支付失败"];
                }
            }
        }];

        
};
    
    
    
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:( NSError *)error{
    NSLog(@"网页加载出错");

}
#pragma 供JS调用的方法
-(void)menthod1{
    NSLog(@"JS调用了无参数OC方法");
}
-(void)menthod2:(NSString *)str1 and:(NSString *)str2{
    NSLog(@"%@%@",str1,str2);
}

// 根据参数生成签名
- (NSString *)genSign:(NSDictionary *)dict
{
    NSMutableString *contentString  =[NSMutableString string];
    NSArray *keys = [dict allKeys];
    //按字母顺序排序
    NSArray *sortedArray = [keys sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        return [obj1 compare:obj2 options:NSNumericSearch];
    }];
    //拼接字符串
    for (NSString *categoryId in sortedArray) {
        if (   ![[dict objectForKey:categoryId] isEqualToString:@""]
            && ![categoryId isEqualToString:@"sign"]
            && ![categoryId isEqualToString:@"key"]
            )
        {
            [contentString appendFormat:@"%@=%@&", categoryId, [dict objectForKey:categoryId]];
        }
    }
    //添加key字段
    [contentString appendFormat:@"key=%@", WeiXinKey];//即创建应用时生成的
    //得到MD5 sign签名
    NSString *md5Sign =[WXUtil md5:contentString];
    return md5Sign;
}




@end
